package cn.jdemo.socket.zeroCopy.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class SocketClient {
    public static void main(String[] args) {
        aioSend(Paths.get("D:\\zerocopy\\hello.txt"));
    }

    public static void aioSend(Path filename) {
        try {
            // 打开一个SocketChannel通道并获取AsynchronousSocketChannel实例
            AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(filename);
            System.out.println(channel.size());
            // 连接到服务器并处理连接结果
            client.connect(new InetSocketAddress("127.0.0.1", 8880), null, new CompletionHandler<Void, Void>() {
                @Override
                public void completed(final Void result, final Void attachment) {
                    System.out.println("成功连接到服务器!");
                    try {
                        ByteBuffer buffer = ByteBuffer.allocate(1024*1024*10);
                        final int[] num = {0};
                        while (num[0] < channel.size()){
                            Future<Integer> rresult = channel.read(buffer, num[0]);
                            Future<Integer> finalRresult = rresult;

                            num[0] = num[0] + finalRresult.get();
                            client.write(buffer);
                            buffer.clear();
                            System.out.println(result+"-------"+num[0]);
                            if(num[0] < 0){
                                break;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void failed(final Throwable exc, final Void attachment) {
                    exc.printStackTrace();
                }
            });
            TimeUnit.MINUTES.sleep(Integer.MAX_VALUE);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
